import { Button, message, Switch, Popconfirm } from 'antd'
import { Table } from '@/desktop/components'
import services from '@/services'
import type { WelcomeConfig } from '@/services/features/normal-welcome'
import './configs.module.less'
import EditConfigModal from './edit-config'

export default function Configs() {
  // ========== 加载列表 ==========
  const [configs, setConfigs] = useState<WelcomeConfig[]>([])
  const [loading, setLoading] = useState(false)
  const loadConfigs = useCallback(async () => {
    setLoading(true)
    const res = await services.features.normalWelcome.loadConfigs()
    if (res.success) setConfigs(res.data)
    else void message.warning('获取任务列表失败')
    setLoading(false)
    return res.success
  }, [])

  useEffect(() => {
    void loadConfigs()
  }, [loadConfigs])

  // ========== 切换状态 ==========
  const [switching, setSwitching] = useState(false)
  const switchStatus = useCallback(
    async (config: WelcomeConfig) => {
      setSwitching(true)

      const res = await services.features.normalWelcome.addOrUpdateConfig({
        ...config,
        enable: !config.enable,
      })
      if (res.success) void message.success('操作成功')
      else void message.warning(`操作失败：${res.error}`)

      await loadConfigs()

      setSwitching(false)
    },
    [loadConfigs],
  )

  // ========== 移除 ==========
  const [removing, setRemoving] = useState(false)
  const remove = useCallback(
    async (id: number) => {
      setRemoving(true)

      const res = await services.features.normalWelcome.removeConfig(id)
      if (res.success) void message.success('删除成功')
      else void message.warning(`删除失败：${res.error}`)

      await loadConfigs()

      setRemoving(false)
    },
    [loadConfigs],
  )

  // ========== 创建/编辑 ==========
  const [editing, setEditing] = useState<WelcomeConfig | true | null>(null)
  const finishEdit = useCallback(() => {
    setEditing(null)
    void loadConfigs()
  }, [loadConfigs])

  // ========== 界面 ==================

  const blocking = loading || removing || switching

  const renderStatus = useCallback(
    (config: WelcomeConfig) => {
      return <Switch
        checked={config.enable}
        onChange={async () => switchStatus(config)}
        checkedChildren="开"
        unCheckedChildren="关"
      />
    },
    [switchStatus],
  )

  const renderActions = useCallback(
    (config: WelcomeConfig) => {
      return <>
        <Button type="link" onClick={() => setEditing(config)}>
          修改
        </Button>
        <Popconfirm title="确定要删除此欢迎语吗？" onConfirm={async () => remove(config.id)}>
          <Button type="link" danger>
            删除
          </Button>
        </Popconfirm>
      </>
    },
    [remove],
  )

  return <div styleName="configs-wrap">
    <header>
      <Button type="primary" onClick={() => setEditing(true)}>
        新建欢迎语
      </Button>
    </header>

    <Table<WelcomeConfig>
      rowKey="id"
      dataSource={configs}
      scroll={{ y: 300 }}
      pagination={false}
      loading={blocking}
    >
      <Table.Column<WelcomeConfig> title="任务名称" width={180} dataIndex="name" />
      <Table.Column<WelcomeConfig> title="状态" key="status" width={80} render={renderStatus} />
      <Table.Column<WelcomeConfig>
        title="操作"
        key="actions"
        width={160}
        styleName="actions"
        render={renderActions}
      />
    </Table>

    <EditConfigModal editing={editing} onFinish={finishEdit} />
  </div>
}
